//
//  TJOrderDetailControntroller.m
//  Teleport
//
//  Created by xtjun on 2020/6/14.
//  Copyright © 2020 xtjun. All rights reserved.
//

#import "TJOrderDetailControntroller.h"
#import "TJOrderDetailHeaderView.h"
#import "TJOrderRecordListModel.h"
#import "TJPaymentDetailController.h"
#import "TJRoundingCornerImageView.h"
#import "TJBigImageController.h"
#import "TJAppealController.h"
#import "TJInputPasswordControntroller.h"
#import "TJSinglePayWayController.h"
#import "TJForgetPasswordController.h"
#import "TJSettingMoneyPasswordController.h"
@interface TJOrderDetailControntroller ()

@property (weak, nonatomic) TJOrderDetailHeaderView *headerView;
@property (strong, nonatomic) NSMutableArray *datas;
@property (strong, nonatomic) TJOrderRecordListModel *model;
@property (weak, nonatomic) UIView *footerView;
@property (weak, nonatomic) UIButton *cancelButton;
@property (weak, nonatomic) UIButton *leftButton;
@property (weak, nonatomic) UIButton *rightButton;
//@property (weak, nonatomic) UIButton *QRCodeButton;

@property (strong, nonatomic) NSMutableArray *payDatas;

//@property (assign, nonatomic) BOOL isFirstLoading;
//@property (weak, nonatomic) UIImage *QRImage;
//
//@property (strong, nonatomic) NSDateFormatter *formatter;
//@property (assign, nonatomic) BOOL isPush;

/**状态 */
@property (assign, nonatomic) int state;

/**订单结束时间 */
@property (assign, nonatomic) NSInteger orderEndTime;
/**服务器当前时间 */
@property (assign, nonatomic) NSInteger nowTime;

/**支付方式数据 */
@property (strong, nonatomic) TJPaymentDetailModel *paymentDetailModel;

//@property (nonatomic, weak) NSTimer *orderTimer;

@end

@implementation TJOrderDetailControntroller {
    dispatch_source_t _timer;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //获取订单数据
    [self loadNewData];
}
//-(void)viewDidDisappear:(BOOL)animated {
//    [super viewDidDisappear:animated];
//    [self.orderTimer setFireDate:[NSDate distantFuture]];
//
//}
//
//-(void)viewWillAppear:(BOOL)animated {
//    [super viewWillAppear:animated];
//
//    [self.orderTimer setFireDate:[NSDate distantPast]];
//
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //    self.isFirstLoading = YES;
    /**禁止右滑退出 */
    self.fd_interactivePopDisabled = YES;
    
    _datas = @[].mutableCopy;
    

    self.navigationBar.title = @"订单详情".localizedString;
    
    TJOrderDetailHeaderView *headerView = [[TJOrderDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 90)];
    headerView.backgroundColor = UIColor.whiteColor;
    self.navigationBar.lineView.hidden = NO;
    self.tableViewStyle = UITableViewStyleGrouped;
    self.tableView.rowHeight = 49;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.backgroundColor = UIColor.whiteColor;
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, TabbarSafeBottomMargin, 0);
    [self.tableView registerClass:TJStyle1Cell.class forCellReuseIdentifier:style1Cell];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.offset(0);
        make.top.offset(KNavBarHight);
    }];
    
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 60)];
    UIButton *cancelButton = [UIButton buttonWithSuperView:footerView font:UIFont_Px(16) color:UIColor.whiteColor title:@""];
    cancelButton.backgroundColor = UIColor.tj_mainColor;
    [cancelButton shearRoundedCornersWithRadiu:3];
    [cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-16);
        make.left.offset(16);
        make.height.offset(44);
        make.center.offset(0);
    }];
    
    /**取消按钮 */
    UIButton *leftButton = [UIButton buttonWithSuperView:footerView font:UIFont_Px(16) color:UIColor_Hex(0x3881E8) title:@""];
    leftButton.backgroundColor = UIColor.whiteColor;
    leftButton.layer.borderColor = UIColor_Hex(0x3881E8).CGColor;
    leftButton.layer.borderWidth = 1;
    [leftButton shearRoundedCornersWithRadiu:3];
    [leftButton addTarget:self action:@selector(didClickLeftButton:) forControlEvents:UIControlEventTouchUpInside];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(footerView.mas_centerX).offset(-10);
        make.left.offset(16);
        make.height.offset(44);
        make.centerY.offset(0);
    }];
    
    /**去付款 */
    UIButton *rightButton = [UIButton buttonWithSuperView:footerView font:UIFont_Px(16) color:UIColor.whiteColor title:@""];
    rightButton.backgroundColor = UIColor_Hex(0x3881E8);
    [rightButton shearRoundedCornersWithRadiu:3];
    [rightButton addTarget:self action:@selector(didClickRightButton:) forControlEvents:UIControlEventTouchUpInside];
    [rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.offset(-16);
        make.left.equalTo(footerView.mas_centerX).offset(10);
        make.height.offset(44);
        make.centerY.offset(0);
    }];
    
    cancelButton.hidden = YES;
    leftButton.hidden = YES;
    rightButton.hidden = YES;
    footerView.hidden = YES;
    
    _footerView = footerView;
    _headerView = headerView;
    _cancelButton = cancelButton;
    _leftButton = leftButton;
    _rightButton = rightButton;
    
    self.tableView.tableFooterView = footerView;
    self.tableView.tableHeaderView = headerView;

    
    
    //    //获取订单数据
    //    [self loadData];
    
    self.tableView.mj_header = self.refreshHeader;
    
//  self.navigationBar.leftBarButton = [TJButtonBarButton barButtonBackButtonTarget:self action:@selector(popController)];
//    NSTimer *orderTimer  =  [NSTimer timerWithTimeInterval:5.0 target:self selector:@selector(oderTimerRun) userInfo:nil repeats:YES];
//       [[NSRunLoop mainRunLoop] addTimer:orderTimer forMode:NSDefaultRunLoopMode];
//    self.orderTimer = orderTimer;
    
    
}

//- (void)oderTimerRun {
//    //获取订单数据
//       [self loadNewData];
//}
//-(void)popController {
//
////    [self.orderTimer invalidate];
////    self.orderTimer = nil;
//    [self.navigationController popViewControllerAnimated:YES];
//}
#pragma mark ---------------取消交易------------------
- (void)didClickLeftButton:(UIButton *)button {
    if (button.tag == 1001) {
        [self alertWithTitle:@"确定取消交易?".localizedString message:@"取消规则：买家当日累计3笔取消，会限制当日买入功能。".localizedString leftButtonName:@"我再想想".localizedString rightButtonName:@"确定".localizedString leftButtonBlock:nil rightButtonBlock:^{
            
            NSDictionary *parameters = @{
                @"priceOrderId": self.orderId,
                @"userId": TJUserInfo.readInfo.userId
            };
            [TJNetworking.shareNetworking POSTNew:@"otc/order/backOrder" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
                [self loadNewData];
            } failure:^(NSError * _Nonnull error) {
                [TJHud showAutoHideMessage:error.localizedFailureReason];
            }];
        }];
        return;
    }
}
#pragma mark ---------------去付款------------------
- (void)didClickRightButton:(UIButton *)button {
    if (button.tag == 1101) {//去付款
        if (!self.paymentDetailModel) {
            [TJHud showAutoHideMessage:@"请选择支付方式".localizedString];
            return;
        }
        TJPaymentDetailController *paymentDetailController = [[TJPaymentDetailController alloc] init];
        paymentDetailController.model = self.paymentDetailModel;
        [self.navigationController pushViewController:paymentDetailController animated:YES];
    }
}
#pragma mark ---------------UITableViewDataSource, UITableViewDelegate>------------------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TJStyle1Cell *cell = [tableView dequeueReusableCellWithIdentifier:style1Cell forIndexPath:indexPath];
    TJCellStyleModel *model = self.datas[indexPath.row];
    cell.model = model;
    cell.tj_textLabel.textColor = UIColor_Hex(0x656565);
    cell.tj_textLabel.font = UIFont_Px(15);
    cell.selectionStyle = model.isNeedCopy ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone;
    cell.tj_detailTextLabel.font = MediumFont(15);
    
    if (indexPath.row == 0) {
        cell.tj_detailTextLabel.textColor = UIColor_Hex(0x3881E7);
    } else {
        cell.tj_detailTextLabel.textColor = UIColor_Hex(0x262626);
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    TJCellStyleModel *model = self.datas[indexPath.row];
    
    if (model.isNeedCopy) {
        [Tools copyStringToPasteboard:model.detailText.replacingEmptyString];
        
    }
    if (model.hasArrow.intValue == 1) {//收款方式
        TJSinglePayWayController *selectPayWayController = [[TJSinglePayWayController alloc] init];
        weakify(self)
        selectPayWayController.model = self.model;
        [selectPayWayController setSelectComplete:^(TJCellStyleModel * _Nonnull model) {
            
            //移除第一次的添加数据
            NSMutableArray *tempArr = [NSMutableArray array];
            for (TJCellStyleModel *allModel in self.datas) {
                if (allModel.isMark == 3) {
                    [tempArr addObject:allModel];
                }
            }
            [self.datas removeObjectsInArray:tempArr];
            
            
            //赋值收款方式
            TJCellStyleModel *payModel = weakself.datas[indexPath.row];
            payModel.detailText = model.text;
            payModel.attributedStringIcon = model.icon;
            
            TJCellStyleModel *accountModel = [TJCellStyleModel new];
            //微信 支付宝
            //赋值 姓名
            for (TJCellStyleModel *accModel in weakself.datas) {
                
                if (accModel.isMark == 1) {// 姓名标记
                    accModel.detailText = model.uname;
                    accountModel.uname = model.uname;
                }
                if (accModel.isMark == 2) {//账号标记
                    accModel.text = [NSString stringWithFormat:@"%@账号".localizedString, model.text];
                    if ([model.identification isEqualToString:@"BANKCARD"]){
                        accModel.detailText = model.bankCard;
                    }else{
                        accModel.detailText = model.name;
                    }
                    
                    accountModel.name = model.name;
                    accountModel.text = accModel.text;
                }
                
            }
            
            //支付二维码
            accountModel.url = model.url;
            if ([model.identification isEqualToString:@"BANKCARD"]) {//选择里银行卡
                
                //添加数据
                TJCellStyleModel *bankNameModel = [TJCellStyleModel cellStyleModelWithText:@"开户银行".localizedString detailText:model.bankName cellClass:@"TJStyle1Cell"];
                bankNameModel.attributedStringIcon = @"detall_copy_icon";
                bankNameModel.isNeedCopy = YES;
                bankNameModel.isMark = 3;
                
                TJCellStyleModel *branchnameModel = [TJCellStyleModel cellStyleModelWithText:@"开户支行".localizedString detailText:model.bankAddress cellClass:@"TJStyle1Cell"];
                branchnameModel.attributedStringIcon = @"detall_copy_icon";
                branchnameModel.isNeedCopy = YES;
                branchnameModel.isMark = 3;
                
                [self.datas addObject:bankNameModel];
                [self.datas addObject:branchnameModel];
                
            }
            accountModel.bankCard = model.bankCard;
            accountModel.bankName =  model.bankName;
            accountModel.bankAddress = model.bankAddress;
            
            //组装支付数据
            self.paymentDetailModel = [TJPaymentDetailModel paymentDetailModelWithTotalPrice:self.model.totalPrice orderEndTime:self.orderEndTime nowTime:self.nowTime payType:model.identification account:accountModel priceOrderId:self.model.id status:self.state userId:self.model.userId];
            
            
            [weakself.tableView reloadData];
            
            
            
        }];
        [self.navigationController presentViewController:selectPayWayController animated:NO completion:nil];
    }
    
}


///**二位码点击 */
//- (void)didClicQrCodeButton {
//
//    [self showloading];
//    NSString *imageUrl =  [self payTypeImageUrlWithPayType:_model.payType];
//    [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:imageUrl] options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
//        if (error) return;
//        self.QRImage = image;
//
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self hiddenloading];
//            TJBigImageController *bigImageController = [[TJBigImageController alloc] init];
//            bigImageController.image = image;
//            [self.navigationController pushViewController:bigImageController animated:YES];
//        });
//
//    }];
//
//
//}

#pragma mark ---------------卖家放行按钮点击------------------
- (void)didClickReleaseButton {
    
    //判断有没有设置交易密码
    
    if (!TJUserInfo.readInfo.payPassword.replacingEmptyString.length) {
        //0，未绑定,1已绑定
        TJSettingMoneyPasswordController *settingMoneyPasswordController = [[TJSettingMoneyPasswordController alloc] init];
        
        [self.navigationController pushViewController:settingMoneyPasswordController animated:YES];
        return;
        
    }
    
    
    TJInputPasswordControntroller *inputPasswordControntroller = [[TJInputPasswordControntroller alloc] init];
    weakify(self)
    [inputPasswordControntroller setSelectComplete:^(NSString * _Nonnull password) {
        NSDictionary *parameters = @{
            @"priceOrderId": self.orderId,
            @"userId": TJUserInfo.readInfo.userId,
            @"pwd": password
        };
        [TJNetworking.shareNetworking POSTNew:@"otc/order/deliverGoods" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
            [self loadNewData];
        } failure:^(NSError * _Nonnull error) {
            [TJHud showAutoHideMessage:error.localizedFailureReason];
        }];
    }];
    [inputPasswordControntroller setForgetPasswordBlock:^{
        TJForgetPasswordController *forgetVC = [TJForgetPasswordController new];
        forgetVC.isPay = YES;
        [weakself.navigationController pushViewController:forgetVC animated:YES];
    }];
    [self presentViewController:inputPasswordControntroller animated:YES completion:nil];
    
    
}
#pragma mark ---------------申诉点击------------------
/**申诉点击 */
- (void)didClickAppealButton {
    TJAppealController *appealController = [[TJAppealController alloc] init];
    appealController.orderId = _model.id;
    [self.navigationController pushViewController:appealController animated:YES];
}

- (void)loadNewData {
    
    if (!_orderId) return;
    
    weakify(self);
    [TJNetworking.shareNetworking POSTNew:@"otc/order/orderEndTime" parameters:@{@"priceOrderId": _orderId} success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        weakself.orderEndTime = [data[@"orderEndTime"] integerValue];
        weakself.nowTime = [data[@"nowTime"] integerValue];
        
        [weakself loadOrderData];
        [weakself.tableView.mj_header endRefreshing];
    } failure:^(NSError * _Nonnull error) {
        [weakself.tableView.mj_header endRefreshing];
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
}


/**订单详情 **/
- (void)loadOrderData {
    
    
    NSDictionary *parameters = @{
        @"priceOrderId": _orderId,
        @"userId": TJUserInfo.readInfo.userId,
    };
    self.footerView.hidden = YES;
    
    [TJNetworking.shareNetworking POSTNew:@"otc/order/orderDetails" parameters:parameters success:^(NSDictionary * _Nonnull responseObject, NSDictionary *data) {
        
        self.model = [TJOrderRecordListModel mj_objectWithKeyValues:data];
        
        [self loadStatusData:self.model];
        
    } failure:^(NSError * _Nonnull error) {
        [TJHud showAutoHideMessage:error.localizedFailureReason];
    }];
    
}

- (void)loadStatusData:(TJOrderRecordListModel *)model {
    NSString *buyCoinTitle = @"";
    if ([model.userId isEqualToString:TJUserInfo.readInfo.userId]) {//自己
        buyCoinTitle = [model.userDirection isEqualToString:@"BUY"] ?  @"购买".localizedString : @"出售".localizedString;
    }else{//卖家
        buyCoinTitle = [model.storeDirection isEqualToString:@"BUY"] ?  @"购买".localizedString : @"出售".localizedString;
    }
    
    //头数据
    self.headerView.tip = [NSString stringWithFormat:@"%@%@", buyCoinTitle,  model.currency];
    
    int state = 0;//1：已完成，2：已取消，3：等待买方付款，4：等待卖方确认，5：自动取消. 6纠纷中
    
    if ([model.appealStatus isEqualToString:@"NORMAL"]) {//没申诉
        // NONPAYMENT--未付款 PAYMENT-- 已付款  --FINISH 完成 --CALLOFF 撤销
        if ([model.status isEqualToString:@"NONPAYMENT"]) {//未付款
            state = 3;
        }else if ([model.status isEqualToString:@"PAYMENT"]){//已付款
            state = 4;
        }else if ([model.status isEqualToString:@"FINISH"]){//完成
            state = 1;
        }else{//CALLOFF 撤销(取消)
            state = 2;
        }
        
    }else if ([model.appealStatus isEqualToString:@"UNDERWAY"]){//申诉中
        state = 6;
    }else if ([model.appealStatus isEqualToString:@"BACK"]){//申诉撤销
        state = 1;
    }else if ([model.appealStatus isEqualToString:@"SUCCEED"]){//申诉成功
        state = 1;
    }else{//申诉失败
        state = 1;
    }
    self.state = state;
    
    
    self.headerView.stateLabel.hidden = YES;
    
    if (state == 1 || state == 4) {
        //订单数据
        [self handleState_1_4];
        //支付方式数据
        [self handlePayAcountWithData:model];
        return;
    }
    
    if (state == 3) {
        [self handleState_3];
        [self handlePayAcountWithData:model];
        return;
    }
    
    if (state == 2 || state == 5) {
        [self handleState_2_5];
        return;
    }
    
    if (state == 6) {
        [self handleState_6];
        [self handlePayAcountWithData:model];
        return;
    }
}

#pragma mark ---------------支付方式model------------------
- (void)handlePayAcountWithData:(TJOrderRecordListModel *)model {
    
    TJCellStyleModel *payeeModel = [TJCellStyleModel cellStyleModelWithText:@"收款人".localizedString detailText:model.storeName cellClass:@"TJStyle1Cell"];
    payeeModel.attributedStringIcon = @"detall_copy_icon";
    
    
    TJCellStyleModel *nameModel = [TJCellStyleModel cellStyleModelWithText:@"姓名".localizedString detailText:model.storeName cellClass:@"TJStyle1Cell"];
    TJCellStyleModel *accountModel = [TJCellStyleModel cellStyleModelWithText:[NSString stringWithFormat:@"%@账号".localizedString, [self payTypeName:model.payType]] detailText:[self payTypeDetailWithModel:_model.payType] cellClass:@"TJStyle1Cell"];
    //给与标记
    nameModel.isMark = 1;
    accountModel.isMark = 2;
    
    nameModel.attributedStringIcon = @"detall_copy_icon";
    accountModel.attributedStringIcon = @"detall_copy_icon";
    /**是否复制 */
    nameModel.isNeedCopy = YES;
    accountModel.isNeedCopy = YES;
    
    //    self.payAccountDict = data;
    [self.datas addObject:nameModel];
    [self.datas addObject:accountModel];
    
    [self.payDatas addObject:payeeModel];
    [self.payDatas addObject:accountModel];
    
    if ([self.model.payType isEqualToString:@"BANKCARD"]) {
        TJCellStyleModel *bankNameModel = [TJCellStyleModel cellStyleModelWithText:@"开户银行".localizedString detailText:model.payMap.BANKCARD.bankName cellClass:@"TJStyle1Cell"];
        bankNameModel.attributedStringIcon = @"detall_copy_icon";
        bankNameModel.isNeedCopy = YES;
        
        TJCellStyleModel *branchnameModel = [TJCellStyleModel cellStyleModelWithText:@"开户支行".localizedString detailText:model.payMap.BANKCARD.bankAddress cellClass:@"TJStyle1Cell"];
        branchnameModel.attributedStringIcon = @"detall_copy_icon";
        branchnameModel.isNeedCopy = YES;
        
        [self.datas addObject:bankNameModel];
        [self.datas addObject:branchnameModel];
        [self.payDatas addObject:bankNameModel];
        [self.payDatas addObject:branchnameModel];
    }
    
    [self.tableView reloadData];
    
    // NSString *imageUrl = [self payTypeImageUrlWithPayType:model.payType];
    //    if (!imageUrl) return;
    //
    //    [[SDWebImageManager sharedManager] loadImageWithURL:[NSURL URLWithString:imageUrl] options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
    //        if (!error) {
    ////            self.QRImage = image;
    //        }
    //    }];
    
}
#pragma mark ---------------自动取消------------------
- (void)handleState_2_5 {//自动取消
    
    [_datas removeAllObjects];
    
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:@"总价".localizedString detailText:[NSString stringWithFormat:@"￥%@", _model.totalPrice] cellClass:@"TJStyle1Cell"]];
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:@"单价".localizedString detailText:[NSString stringWithFormat:@"￥%@", _model.price] cellClass:@"TJStyle1Cell"]];
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:@"数量".localizedString detailText:[NSString stringWithFormat:@"%@%@", _model.num, _model.currency] cellClass:@"TJStyle1Cell"]];
    
    TJCellStyleModel *model = [TJCellStyleModel cellStyleModelWithText:@"订单号".localizedString detailText:_model.id cellClass:@"TJStyle1Cell"];
    model.attributedStringIcon = @"detall_copy_icon";
    model.isNeedCopy = YES;
    model.attributedStringIconSize = [NSValue valueWithCGSize:CGSizeMake(18, 18)];
    [_datas addObject:model];
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:[self nameType] detailText:_model.storeName cellClass:@"TJStyle1Cell"]];
    
    TJCellStyleModel *payModel = [TJCellStyleModel cellStyleModelWithText:@"收款方式".localizedString detailText:[self payTypeName:_model.payType] cellClass:@"TJStyle1Cell"];
    payModel.attributedStringIcon = [self payTypeIcon:_model.payType];
    payModel.isIconINPrevious = YES;
    [_datas addObject:payModel];
    
    
    _headerView.titleLabel.text =  @"交易取消".localizedString;
    _headerView.subTitleLabel.textColor = UIColor_Hex(0x666666);
    _headerView.subTitle = @"订单取消无法查看支付信息".localizedString;
    
    _headerView.tj_height = 125;
    
    self.tableView.tableHeaderView = _headerView;
    [self.tableView reloadData];
}
#pragma mark ---------------纠纷中------------------
- (void)handleState_6 {//纠纷中
    
    [_datas removeAllObjects];
    
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:@"总价".localizedString detailText:[NSString stringWithFormat:@"￥%@", _model.totalPrice] cellClass:@"TJStyle1Cell"]];
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:@"单价".localizedString detailText:[NSString stringWithFormat:@"￥%@", _model.price] cellClass:@"TJStyle1Cell"]];
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:@"数量".localizedString detailText:[NSString stringWithFormat:@"%@%@", _model.num, _model.currency] cellClass:@"TJStyle1Cell"]];
    
    TJCellStyleModel *model = [TJCellStyleModel cellStyleModelWithText:@"订单号".localizedString detailText:_model.id cellClass:@"TJStyle1Cell"];
    model.attributedStringIcon = @"detall_copy_icon";
    model.attributedStringIconSize = [NSValue valueWithCGSize:CGSizeMake(18, 18)];
    model.isNeedCopy = YES;
    [_datas addObject:model];
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:[self nameType] detailText:_model.storeName cellClass:@"TJStyle1Cell"]];
    
    TJCellStyleModel *payModel = [TJCellStyleModel cellStyleModelWithText:@"收款方式".localizedString detailText:[self payTypeName:_model.payType] cellClass:@"TJStyle1Cell"];
    payModel.attributedStringIcon = [self payTypeIcon:_model.payType];
    payModel.isIconINPrevious = YES;
    [_datas addObject:payModel];
    
    
    _headerView.titleLabel.text = @"纠纷中".localizedString;
    _headerView.subTitle = @"请耐心等待客服处理".localizedString;
    
    _headerView.tj_height = 125;
    self.tableView.tableHeaderView = _headerView;
    [self.tableView reloadData];
    
}

#pragma mark ---------------已完成------------------
- (void)handleState_1_4 {//已完成
    
    [_datas removeAllObjects];
    
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:@"总价".localizedString detailText:[NSString stringWithFormat:@"￥%@", _model.totalPrice] cellClass:@"TJStyle1Cell"]];
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:@"单价".localizedString detailText:[NSString stringWithFormat:@"￥%@", _model.price] cellClass:@"TJStyle1Cell"]];
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:@"数量".localizedString detailText:[NSString stringWithFormat:@"%@%@", _model.num, _model.currency] cellClass:@"TJStyle1Cell"]];
    
    TJCellStyleModel *model = [TJCellStyleModel cellStyleModelWithText:@"订单号".localizedString detailText:_model.id cellClass:@"TJStyle1Cell"];
    model.attributedStringIcon = @"detall_copy_icon";
    model.isNeedCopy = YES;
    [_datas addObject:model];
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:[self nameType] detailText:_model.storeName cellClass:@"TJStyle1Cell"]];
    
    TJCellStyleModel *payModel = [TJCellStyleModel cellStyleModelWithText:@"收款方式".localizedString detailText:[self payTypeName:_model.payType] cellClass:@"TJStyle1Cell"];
    payModel.attributedStringIcon = [self payTypeIcon:_model.payType];
    payModel.isIconINPrevious = YES;
    [_datas addObject:payModel];
    
    if (self.state == 4) {//已完成, 隐藏下面按钮 //判断是否超时,超时了显示已超时, 和申诉
        
        if ([self userTypeVule] == 1) {//买
            
            _headerView.titleLabel.text = @"等待卖家确认".localizedString;
            
            _cancelButton.hidden = NO;
            _leftButton.hidden = YES;
            _rightButton.hidden = YES;
            
            
            self.footerView.hidden = NO;
            [self.cancelButton setTitle:@"申诉".localizedString forState:UIControlStateNormal];
            self.cancelButton.backgroundColor = UIColor_Hex(0xFF0000);
            [self.cancelButton addTarget:self action:@selector(didClickAppealButton) forControlEvents:UIControlEventTouchUpInside];
            
            
            //            NSDate *outTimeDate = [_formatter dateFromString:_model.createTime];
            //            NSInteger currentTimestamp = (NSInteger)[[NSDate date] timeIntervalSince1970];
            //            NSInteger outTimeTimestamp = outTimeDate.timeIntervalSince1970;
            //
            //            if (currentTimestamp > outTimeTimestamp) {//已超时
            //
            
            //                self.footerView.hidden = NO;
            //                [self.cancelButton setTitle:@"申诉".localizedString forState:UIControlStateNormal];
            //                self.cancelButton.backgroundColor = UIColor_Hex(0xFF0000);
            //                [self.cancelButton addTarget:self action:@selector(didClickAppealButton) forControlEvents:UIControlEventTouchUpInside];
            //
            
            //显示倒计时, 显示申诉
            //                NSString *stateStr = @"已超时".localizedString;
            //                _headerView.stateLabel.backgroundColor = UIColor_Hex(0xdae5f8);
            //                _headerView.stateLabel.hidden = NO;
            //                CGFloat W = [stateStr getStringSizeWithWidth:200 font:self.headerView.stateLabel.font].width + 30;
            //                [self.headerView.stateLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            //                    make.width.offset(W);
            //                }];
            //
            //                self.headerView.stateLabel.text = stateStr;
            //            } else {
            //
            //                [self showCountdown];
            //            }
            
            //            TJLog(@"currentTimestamp = %ld",(long)currentTimestamp);
            //            TJLog(@"matchingTimestamp = %ld",(long)outTimeTimestamp);
            //
            //
        } else {//卖
            _headerView.titleLabel.text = @"待放行".localizedString;
            _cancelButton.hidden = NO;
            _leftButton.hidden = YES;
            _rightButton.hidden = YES;
            self.footerView.hidden = NO;
            self.cancelButton.backgroundColor = UIColor_Hex(0x3781E7);
            [self.cancelButton setTitle:@"放行".localizedString forState:UIControlStateNormal];
            [self.cancelButton addTarget:self action:@selector(didClickReleaseButton) forControlEvents:UIControlEventTouchUpInside];
            
#pragma mark ---------------卖家没有超时时间------------------
            //卖家没有超时时间
            //            NSDate *outTimeDate = [_formatter dateFromString:_model.createTime];
            //            NSInteger currentTimestamp = (NSInteger)[[NSDate date] timeIntervalSince1970];
            //            NSInteger outTimeTimestamp = outTimeDate.timeIntervalSince1970;
            //
            //            if (currentTimestamp > outTimeTimestamp) {//已超时
            //
            //                self.footerView.hidden = NO;
            //                [self.cancelButton setTitle:@"申诉".localizedString forState:UIControlStateNormal];
            //                self.cancelButton.backgroundColor = UIColor_Hex(0xFF0000);
            //                [self.cancelButton addTarget:self action:@selector(didClickAppealButton) forControlEvents:UIControlEventTouchUpInside];
            //
            //                //显示倒计时, 显示申诉
            //                NSString *stateStr = @"已超时".localizedString;
            //                _headerView.stateLabel.backgroundColor = UIColor_Hex(0xdae5f8);
            //                _headerView.stateLabel.hidden = NO;
            //                CGFloat W = [stateStr getStringSizeWithWidth:200 font:self.headerView.stateLabel.font].width + 30;
            //                [self.headerView.stateLabel mas_updateConstraints:^(MASConstraintMaker *make) {
            //                    make.width.offset(W);
            //                }];
            //
            //            } else {
            //                [self showCountdown];
            //            }
            
        }
    } else {
        _headerView.titleLabel.text = @"交易成功".localizedString;
        
    }
    
    _headerView.tj_height = 90;
    self.tableView.tableHeaderView = _headerView;
    [self.tableView reloadData];
}
#pragma mark ---------------待付款------------------
- (void)handleState_3 {//待付款
    
    [_datas removeAllObjects];
    
    _payDatas = @[].mutableCopy;
    
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:@"总价".localizedString detailText:[NSString stringWithFormat:@"￥%@", _model.totalPrice] cellClass:@"TJStyle1Cell"]];
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:@"单价".localizedString detailText:[NSString stringWithFormat:@"￥%@", _model.price] cellClass:@"TJStyle1Cell"]];
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:@"数量".localizedString detailText:[NSString stringWithFormat:@"%@%@", _model.num, _model.currency] cellClass:@"TJStyle1Cell"]];
    
    TJCellStyleModel *model = [TJCellStyleModel cellStyleModelWithText:@"订单号".localizedString detailText:_model.id cellClass:@"TJStyle1Cell"];
    model.attributedStringIcon = @"detall_copy_icon";
    model.isNeedCopy = YES;
    [_datas addObject:model];
    [_datas addObject:[TJCellStyleModel cellStyleModelWithText:[self nameType] detailText:_model.storeName cellClass:@"TJStyle1Cell"]];
    
    TJCellStyleModel *payModel = [TJCellStyleModel cellStyleModelWithText:@"收款方式".localizedString detailText:[self payTypeName:_model.payType] cellClass:@"TJStyle1Cell"];
    //    payModel.attributedStringIcon = [self payTypeIcon];
    //    /**yes 是左 */
    payModel.isIconINPrevious = YES;
    payModel.hasArrow = @"1";
    [_datas addObject:payModel];
    
    
    _leftButton.hidden = YES;
    _rightButton.hidden = YES;
    
    if ([self userTypeVule] == 1) {//买
        
        _leftButton.hidden = NO;
        _rightButton.hidden = NO;
        _headerView.titleLabel.text = @"待付款".localizedString;
        [_leftButton setTitle:@"取消订单".localizedString forState:UIControlStateNormal];
        [_rightButton setTitle:@"去付款".localizedString forState:UIControlStateNormal];
        _leftButton.tag = 1001;
        _rightButton.tag = 1101;
        _footerView.hidden = NO;
        
        
        if (self.orderEndTime <= self.nowTime) {//已超时
            //显示倒计时, 显示申诉
            
            _footerView.hidden = YES;
            
            NSString *stateStr = @"已超时".localizedString;
            _headerView.stateLabel.backgroundColor = UIColor_Hex(0xdae5f8);
            _headerView.stateLabel.hidden = NO;
            CGFloat W = [stateStr getStringSizeWithWidth:200 font:self.headerView.stateLabel.font].width + 30;
            [self.headerView.stateLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.offset(W);
            }];
            self.headerView.stateLabel.text = stateStr;
            
        } else {
            [self showCountdown];//倒计时
        }
        
    } else {//卖
        
        //        [_QRCodeButton removeFromSuperview];//移除二维码按钮
        
        _headerView.titleLabel.text = @"等待买家付款".localizedString;
        
        //                TJRoundingCornerButton *QRCodeButton = [TJRoundingCornerButton roundingCorners:UIRectCornerTopLeft | UIRectCornerBottomLeft radius:18];
        //                [QRCodeButton addTarget:self action:@selector(didClicQrCodeButton) forControlEvents:UIControlEventTouchUpInside];
        //                [_footerView addSubview:QRCodeButton];
        //                QRCodeButton.titleLabel.font = UIFont_Px(16);
        //                [QRCodeButton setImage:[UIImage imageNamed:@"payDetailQRcodeIcon"] forState:UIControlStateNormal];
        //                [QRCodeButton setImage:[UIImage imageNamed:@"payDetailQRcodeIcon"] forState:UIControlStateHighlighted];
        //                QRCodeButton.backgroundColor = [UIColor.blackColor colorWithAlphaComponent:0.4];
        //                [QRCodeButton setTitle:@"收款码".localizedString forState:UIControlStateNormal];
        //                [QRCodeButton setImagePosition:LXMImagePositionLeft spacing:5];
        //                [QRCodeButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        //                [QRCodeButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        //                [QRCodeButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
        //                [QRCodeButton mas_makeConstraints:^(MASConstraintMaker *make) {
        //                    make.right.offset(0);
        //                    make.centerY.offset(0);
        //                    make.width.offset(100);
        //                    make.height.offset(36);
        //                }];
        //                _footerView.hidden = NO;
        //                _QRCodeButton = QRCodeButton;
        
        if (self.orderEndTime <= self.nowTime) {//已超时
            //显示倒计时, 显示申诉
            NSString *stateStr = @"已超时".localizedString;
            _headerView.stateLabel.backgroundColor = UIColor_Hex(0xdae5f8);
            _headerView.stateLabel.hidden = NO;
            CGFloat W = [stateStr getStringSizeWithWidth:200 font:self.headerView.stateLabel.font].width + 30;
            [self.headerView.stateLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                make.width.offset(W);
            }];
            self.headerView.stateLabel.text = stateStr;
            
        } else {
            [self showCountdown];
        }
        
    }
    
    _headerView.tj_height = 90;
    self.tableView.tableHeaderView = _headerView;
    [self.tableView reloadData];
}
#pragma mark ---------------类型转换------------------

- (NSString *)payTypeIcon:(NSString *)payType {
    
    if ([payType isEqualToString:@"WECHAT"]) {
        return @"OTC_list_weChat";
        
    } else if ([payType isEqualToString:@"ALIAY"]) {
        return @"OTC_list_Alipay";
        
    } else if ([payType isEqualToString:@"BANKCARD"]) {
        return @"OTC_list_bank";
    }  else {
        return @"";
    }
}

//支付图片链接
- (NSString *)payTypeImageUrlWithPayType:(NSString *)payType {
    
    
    if ([payType isEqualToString:@"ALIAY"]) {
        return _model.payMap.ALIAY.url;
    } else if ([payType isEqualToString:@"WECHAT"]) {
        return _model.payMap.WECHAT.url;
    }else{
        return @"";
    }
    
}
/**支付账号 */
- (NSString *)payTypeDetailWithModel:(NSString *)payType {
    
    
    if ([payType isEqualToString:@"ALIAY"]) {
        return _model.payMap.ALIAY.name;
    }else if ([payType isEqualToString:@"BANKCARD"]) {
        return _model.payMap.BANKCARD.bankCard;
    }else if ([payType isEqualToString:@"WECHAT"]) {
        return _model.payMap.WECHAT.name;
    }else{//没有
        
        return @"";
        
    }
    
}
//支付名称 
- (NSString *)payTypeName:(NSString *)payType {
    
    if ([_model.payType isEqualToString:@"ALIAY"]) {
        return @"支付宝".localizedString;
    }else if ([_model.payType isEqualToString:@"BANKCARD"]) {
        return @"银行卡".localizedString;
    }else if ([_model.payType isEqualToString:@"WECHAT"]) {
        return @"微信".localizedString;
    }else{//没有
        
        return @"";
        
    }
}


- (NSString *)nameType {
    if ([_model.userId isEqualToString:TJUserInfo.readInfo.userId]) {//相等的话是自己
        return @"卖家昵称".localizedString;
    }  else {
        return @"买家昵称".localizedString;
    }
}

- (NSInteger)userTypeVule {

    if ([_model.userId isEqualToString:TJUserInfo.readInfo.userId]) {//自己
           NSInteger type = [_model.userDirection isEqualToString:@"BUY"] ?  1 : 2;
          return type;
       }else{//卖家
            NSInteger type = [_model.storeDirection isEqualToString:@"BUY"] ?  1: 2;
            return type;
       }

//     return 1;
//    if ([_model.userId isEqualToString:TJUserInfo.readInfo.userId]) {//相等的话是自己
//
//        return 1;
//    }  else {
//        return 2;
//    }
}

/**倒计时 */
- (void)showCountdown {
    
    if (self -> _timer) {
        dispatch_source_cancel(self -> _timer);
    }
    
    _headerView.stateLabel.backgroundColor = UIColor_Hex(0xdae5f8);
    _headerView.stateLabel.hidden = NO;
    
    __block NSInteger timestamp = (self.orderEndTime - self.nowTime)/1000;//倒计时s数
    
    if (timestamp < 0) return;
    
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        
        timestamp--;
        
        if (timestamp <= 0) {
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{//显示GO
                [[NSNotificationCenter defaultCenter] postNotificationName:refreshOrderListNotification object:nil];
                [self loadNewData];
            });
        } else {
            
            NSString *countdownValue = [Tools videoLengthWithSeconds:timestamp];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (self.state == 3) {//待买家付款
                    NSString *stateStr = [NSString stringWithFormat:@"%@%@", @"待付剩余时间".localizedString, countdownValue];
                    CGFloat W = [stateStr getStringSizeWithWidth:200 font:self.headerView.stateLabel.font].width + 30;
                    [self.headerView.stateLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.width.offset(W);
                    }];
                    self.headerView.stateLabel.text = stateStr;
                } else  if (self.state == 4) {//待买家付款
                    NSString *stateStr = [NSString stringWithFormat:@"%@%@",@"放行剩余时间".localizedString, countdownValue];
                    CGFloat W = [stateStr getStringSizeWithWidth:200 font:self.headerView.stateLabel.font].width + 30;
                    [self.headerView.stateLabel mas_updateConstraints:^(MASConstraintMaker *make) {
                        make.width.offset(W);
                    }];
                    self.headerView.stateLabel.text = stateStr;
                }
                
            });
        }
    });
    _timer = timer;
    dispatch_resume(timer);
}
- (void)dealloc {
     _timer = nil;
    if (_timer) {
        dispatch_source_cancel(_timer);
    }

    NSLog(@"---invalidate----");
}


@end
